package org.yty.travelagencymongodb.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.DTO.HistoryMessageQueryDTO;
import org.yty.travelagencymongodb.model.Entity.Message;
import org.yty.travelagencymongodb.repository.MessageRepository;
import org.yty.travelagencymongodb.service.MessageService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {
    private final MessageRepository messageRepository;

    @Override
    public void save(Message message) {
        message.setCreateTime(LocalDateTime.now());
        this.messageRepository.save(message);
    }

    @Override
    public List<Message> getHistoryMessages(HistoryMessageQueryDTO historyMessageQueryDTO) {
        Pageable pageable = PageRequest.of(historyMessageQueryDTO.getPageNo().intValue(), 10, Sort.by(Sort.Direction.DESC, "createTime"));
        Stream<Message> messageStream = this.messageRepository.findBySenderIdAndReceiverId(historyMessageQueryDTO.getSenderId(), historyMessageQueryDTO.getReceiverId(), pageable).get();
        return messageStream.toList();
    }

    @Override
    public List<Message> getMessages(Long senderId, Long receiverId) {
        return this.getHistoryMessages(new HistoryMessageQueryDTO(senderId,receiverId,1L));
    }
}
